package cn.huanba.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class ImageUtil {
    static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();

    /**
     * 图片->字符
     *
     * @param file
     * @param formatName 图片类型（jpg gif  png）
     * @return
     */

    public static String getImageBinary(File file, String formatName) {
        try {
            BufferedImage bi = ImageIO.read(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, formatName, baos);
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串-->图片
     *
     * @param base64String 图片字符串
     * @param file         存储图片文件
     * @param formatName   图片类型（jpg gif  png）
     */
    public static void base64StringToImage(String base64String, File file, String formatName) {
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            ImageIO.write(bi1, formatName, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
